<template>
  <div :class="className" :style="{height:height,width:width}" />
</template>

<script>
var echarts = require('echarts/lib/echarts')
// 引入 ECharts 主模块
require('echarts/lib/chart/bar')
// 引入提示框和标题组件
require('echarts/lib/component/tooltip')
require('echarts/lib/component/title')
require('echarts/lib/component/legend')
// require('echarts/theme/macarons') // echarts theme
import { debounce } from '@/utils'
// import { themeColor } from '@/assets/echarts/theme'

export default {
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '100%'
    },
    echatsData: {
      type: Array,
      default: () => ([])
    }
  },
  data() {
    return {
      chart: null
    }
  },
  watch: {
    'echatsData': function() {
      this.initChart()
    }
  },
  mounted() {
    this.initChart()
    this.__resizeHandler = debounce(() => {
      if (this.chart) {
        this.chart.resize()
      }
    }, 100)
    window.addEventListener('resize', this.__resizeHandler)
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    window.removeEventListener('resize', this.__resizeHandler)
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')
      this.chart.setOption({
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c}'
        },
        color: '#1890ff',
        xAxis: {
          type: 'category',
          data: this.echatsData.map(ele => ele.alarmDesc),
          axisLabel: {
            isntrval: 0,
            fontSize: 10,
            showMinLabel: true,
            rotate: -20,
            formatter: function(value) {
              const reg = /.{1,24}/g
              return value.length > 23 ? value.match(reg)[0] + '...' : value
            }
          }
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          data: this.echatsData.map(ele => ele.count),
          type: 'bar',
          showBackground: true,
          barWidth: '30',
          label: {
            show: true,
            position: 'insideBottom',
            rotate: 90,
            distance: 15,
            verticalAlign: 'middle',
            align: 'left'
          },
          backgroundStyle: {
            color: 'rgba(220, 220, 220, 0.8)'
          }
        }]
      })
    }
  }
}
</script>
